/**
 * 分页查询对象
 */

package ms.core.db.mysql;

import java.util.ArrayList;
import java.util.List;

import ms.core.db.mysql.DbConfTool.DbType;

public class QueryParam {
	private String cntSql;
	private String qrySql;
	private int page;
	private int pagesize;
	private List<Object> params;

	public static QueryParam getInstance() { return new QueryParam(); }

	public QueryParam() {
		params = new ArrayList<>();
	}

	public String getCntSql() { return cntSql; }
	public QueryParam setCntSql(String cntSql) { 
		this.cntSql = cntSql; 
		return this;
	}

	/**
	 * MSSQL分页查询(OFFSET表示跳过记录数; FETCH NEXT表示页大小)
	 * 注意: MSSQL分页查询，必须要有 order by
	 *   SELECT * FROM YourTableName ORDER BY YourSortColumn
	 *   	OFFSET 40 ROWS FETCH NEXT 10 ROWS ONLY;
	 *   
	 * @param dbType
	 * @return
	 */
	public String getQrySql(DbType dbType) { 
		String sqlLimit = (dbType==DbType.dbMySql) ? 
				String.format(" limit %d,%d", (page-1) * pagesize, pagesize) : 
				String.format(" OFFSET %d ROWS FETCH NEXT %d ROWS ONLY", (page-1) * pagesize, pagesize);
		return (page>0 && pagesize>0) ? (qrySql + sqlLimit) : qrySql;
	}
	public QueryParam setQrySql(String qrySql) { 
		this.qrySql = qrySql;
		return this;
	}

	public QueryParam addParam(Object... values) {
		for(Object v: values) params.add(v);
		return this;
	}
	
	public List<Object> getParams(){ return params; }
	
	public QueryParam setPage(int page, int pagesize) {
		this.page = page;
		this.pagesize = pagesize;
		return this;
	}
	public int getPage() { return this.page; }
	public int getPagesize() { return this.pagesize; }
}
